package cn.datawin.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;

public class DataSource {
	
	private String hosts;
	private String username;
	private String password;
	private String db;
	private String port;
	Mongo mongo;
	
	public DataSource() throws IOException {
		Resource resource = new Resource("/mongodb_2.properties");
		InputStream in =  resource.getInputStream();
		init(in);
	}
	
	public DataSource(String file) throws IOException{
		InputStream in = new FileInputStream(new File(file));
		init(in);
	}
	
	public void init(InputStream in) throws IOException{
		Properties pro = new Properties();
		pro.load(in);
		db = pro.getProperty("db");
		port = pro.getProperty("port");
		hosts = pro.getProperty("hosts");
		username = pro.getProperty("username");
		password = pro.getProperty("password");
	}
	
	public DB getDB(){
		try {
			mongo=new MongoClient(hosts, Integer.parseInt(port));
			DB db= mongo.getDB(this.db);
			if(db.authenticate(username, password.toCharArray())){
				System.out.println("spiderData::用户名和密码正确！");
				return db;
			}
			System.out.print("用户名密码错误");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void destory(){
		this.mongo.close();
	}

	public String getHosts() {
		return hosts;
	}

	public void setHosts(String hosts) {
		this.hosts = hosts;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getDb() {
		return db;
	}

	public void setDb(String db) {
		this.db = db;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}
}
